using Microsoft.AspNetCore.Mvc;
using System.Collections.Generic;
using System.Linq;
using Exercise.Api.Entity;
using Exercise.Api.ParamModel;
using Newtonsoft.Json;
using System;
using Exercise.Api.Repository;
using Microsoft.Extensions.Configuration;
using Exercise.Api.Utils;
using Microsoft.AspNetCore.Authorization;

namespace Exercise.Api.Controllers
{
    // [Authorize]
    [ApiController]
    [Route("[controller]")]
    public class UsersController : ControllerBase
    {
        private IRepository<Users> _usersRespository;
        private TokenParamenter _tokenParameter;
        private readonly IConfiguration _configuration;

        public UsersController(IConfiguration configuration, IRepository<Users> usersRespository)
        {

            _configuration = configuration;
            _usersRespository = usersRespository;
            _tokenParameter = _configuration.GetSection("TokenParameter").Get<TokenParamenter>();
        }

        //获取所有用户
        [HttpGet]
        public dynamic Get([FromQuery] Pager pager)
        {
            //使用传参的方法向前端传输数据(这个方法需要可以自己定义参数)
            // int pagerIndex=1,int PagerSize=10 

            //localhost:5000/users?pagerIndex=1&pagerSize=10&rowsTotal=30
            //使用这个方法获取所有用户时要传参
            var pageIndex = pager.PagerIndex;
            var pageSize = pager.PagerSize;

            //获得所有满足条件的记录
            var users = _usersRespository.Table.Where(x => x.IsDeleted == false);
            //对获取的记录分页
            var u = users.Skip((pageIndex - 1) * pageSize).Take(pageSize).ToList();
            //返回数据(带有分页信息)
            var res = new
            {
                Code = 1000,
                Data = new { Data = u, Pager = new { pagerIndex = pageIndex, pagerSize = pageSize, rowsTotal = users.Count() } },
                Msg = "获取所有用户成功！"
            };
            return res;
        }

        //根据ID查找用户
        [HttpGet("{id}")]
        public dynamic GetId(int id)
        {
            //获取在Users中搜索到的第一个符合条件的数据
            var user = _usersRespository.GetById(id);
            if (user == null)
            {
                return new
                {
                    Code = 1000,
                    Data = user,
                    Msg = "要查找的用户不存在，请确认后重试！"
                };
            }
            else
            {
                return new
                {
                    Code = 1000,
                    Data = user,
                    Msg = "查找用户成功！"
                };
            }

        }

        //创建用户
        [HttpPost]
        public string Created(NewUser model)
        {
            // JsonSerializerSettings settings = new JsonSerializerSettings();
            // settings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
            var username = model.UserName.Trim();
            var password = model.PassWord.Trim();
            var remarks = model.Remarks.Trim();

            if (string.IsNullOrEmpty(username))
            {
                var tmp = new
                {
                    Code = 1004,
                    Data = "",
                    Msg = "用户名不能为空，请确认后重试！"
                };
                return JsonHelper.Serialize(tmp);
            }

            //获取要创建的用户名和密码
            var user = new Users
            {
                UserName = username,
                PassWord = password,
                Remarks = remarks
            };

            //把创建的用户名和密码添加到Users
            _usersRespository.Insert(user);

            var res = new
            {
                Code = 1000,
                Data = user,
                Msg = "创建用户成功！"
            };
            return JsonHelper.Serialize(res);
        }

        //根据ID修改用户
        [HttpPut("{id}")]
        public dynamic Updated(int id, NewUser model)
        {
            //获取要查找的用户id
            var user = _usersRespository.GetById(id);

            if (user != null)
            {
                user.UserName = model.UserName;
                // user.PassWord = model.PassWord;
                user.Remarks=model.Remarks;
                user.UpdatedTime = DateTime.Now;

                //把修改后的数据传入Users表
                _usersRespository.Update(user);

                return JsonHelper.Serialize(new
                {
                    Code = 1000,
                    Data = user,
                    Msg = string.Format("id为{0}的用户已修改成功，请注意查验！", id)
                });
            }
            else
            {
                return JsonHelper.Serialize(new
                {
                    Code = 104,
                    Data = "",
                    Msg = string.Format("id为{0}的用户不存在，无法修改，请确认后重试！", id)
                });
            }
        }

        //根据ID删除用户
        [HttpDelete("{id}")]
        public dynamic Deleted(int id)
        {
            //查找要删除的用户id并返回
            var user = _usersRespository.GetById(id);

            if (user != null)
            {
                //删除指定的id
                _usersRespository.Delete(id);
                return new
                {
                    Code = 1000,
                    Msg = string.Format("用户{0}删除成功！", id)
                };
            }
            else
            {
                return new
                {
                    Code = 104,
                    Data = "",
                    Msg = string.Format("要删除的用户{0}不存在，请确认后重试！", id)
                };
            }

        }

        //获取创建的表，并传入数据
        private IEnumerable<Users> GetUsers()
        {
            var users = new List<Users>{
                new Users{
                    Id=1,
                    UserName="admin",
                    PassWord="123"
                },
                new Users{
                    Id=2,
                    UserName="abc",
                    PassWord="123"
                },
                new Users{
                    Id=3,
                    UserName="adf",
                    PassWord="123"
                }
            };
            return users;
        }

        [AllowAnonymous]
        //用户登录，获取token
        [HttpPost, Route("token")]
        public dynamic GetToken(NewUser model)
        {

            //获取输入的用户名和密码
            var Username = model.UserName.Trim();
            var Password = model.PassWord.Trim();

            //查找对应的用户名和密码并返回(只查找一个)
            var user = _usersRespository.Table.Where(x => x.UserName == Username && x.PassWord == Password).FirstOrDefault();

            if (user == null)
            {
                return new
                {
                    Code = 1001,
                    Data = user,
                    Msg = "用户名或密码不正确，请确认后重试！"
                };
            }

            var token = TokenHelper.GenerateToken(_tokenParameter, user);
            var refreshToken = "123456";

            var res = new
            {
                Code = 1000,
                Data = new { Token = token, RefreshToken = refreshToken },
                Msg = "登录成功，获取token成功"
            };

            return res;
        }
    }
}